import React, { useState } from 'react'

export default function App() {
  const [text, setText] = useState('')
  const [output, setOuput] = useState('')
  const [adjacents, setAdjacent] = useState('')
  const statistics = () => {
    console.log('按钮');
    const texs = text.toLocaleLowerCase().match(/\w+/g);
    if (!texs) {
      setOuput('')
      setAdjacent('')
      return
    }
    // 统计单词的频率
    const countWords = {}
    for (const statistic of texs) {
      if (countWords[statistic]) {
        countWords[statistic]++
      } else {
        countWords[statistic] = 1
      }
    }
    // 统计相邻的词的评率
    const adjacent = {};
    for (let i = 0; i < texs.length - 1; i++) {
      const adjacentWord = `${texs[i]} ${texs[i + 1]}`
      if (adjacent[adjacentWord]) {
        adjacent[adjacentWord]++
      } else {
        adjacent[adjacentWord] = 1
      }
    }
    let result = []
    let results = ""
    for (const [word, count] of Object.entries(countWords)) {
      result += `${word}: ${count}`;
    }
    for (const [adjacentwords, count] of Object.entries(adjacent)) {
      results += `${adjacentwords}:${count}`

    }
    return [setOuput(result),
    setAdjacent(results)]
  }
  return (
    <div>
      <textarea name="" id="" value={text} placeholder='请输入文本' onChange={(e) => {
        setText(e.target.value)
      }} ></textarea>
      <button onClick={statistics}>统计</button>

      <h3>单词的评率:{output}</h3>
      <h3>相邻的单词评率：{adjacents}</h3>


    </div>
  )

}
